﻿using System;

namespace Carbon.Web.Forms.Controls
{
    public class ModelValue : ViewControlBase
    {
		#region Fields (3)
		private bool m_HtmlEscape = true;

		private String m_Format = "{0}";
		private String m_Value = string.Empty;
		#endregion

		#region Events (1)
		public event EventHandler<BindEventArgs> UpdatingControl;
		#endregion

		#region Properties (2)
		public String Format
        {
            get
            {
                return m_Format;
            }
            set
            {
                m_Format = value;
            }
        }
		public bool HtmlEscape
        {
            get
            {
                return m_HtmlEscape;
            }
            set
            {
                m_HtmlEscape = value;
            }
        }
		#endregion

		#region ASP Processing

		public override void RenderControl(System.Web.UI.HtmlTextWriter writer)
        {
            if (m_Value == null)
                m_Value = "";

            if (HtmlEscape)
            {
                writer.WriteEncodedText(m_Value);
            }
            else
            {
                writer.Write(m_Value);
            }
        }

		#endregion

		#region Methods (3)

		protected override IEditor CreateEditor()
        {
            return null;
        }

		public override void OnUpdateControl(object sender, UpdateControlEventArgs args)
        {
            base.OnUpdateControl(sender, args);

            Object value = Binder.Value;

            BindEventArgs args2 = new BindEventArgs(value);
            OnUpdatingControl(args2);
            value = args2.ReturnValue;

            m_Value = string.Format(Format, value);

            if (m_Value == null)
                m_Value = string.Empty;
        }

		protected virtual void OnUpdatingControl(BindEventArgs args)
        {
            if (UpdatingControl != null)
            {
                UpdatingControl(this, args);
            }
        }

		#endregion
    }
}
